
package com.hsc.www.rawTest;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class Producer {
    public static void main(String[] args) throws Exception {
        //1、创建ConnectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setVirtualHost("my_vhost");
        connectionFactory.setPort(5672);

        //2、获取 connection
        Connection connection = connectionFactory.newConnection();

        //3、通过connection创建一个新的Channel
        Channel channel = connection.createChannel();

        //4、指定我们的消息投递模式: 消息的确认模式
        channel.confirmSelect();

        String QUEUE_NAME = "confirm_queue";
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        //5 发送一条消息
        String msg = "Hello RabbitMQ Send confirm message!";

        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    channel.basicPublish("", QUEUE_NAME, null, msg.getBytes());
                    TimeUnit.NANOSECONDS.sleep(1L * i);
                }
            } catch (Exception e) {
            }
        }).start();

        //6 添加一个确认监听
        channel.addConfirmListener(new ConfirmListener() {
            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                System.err.println("-------no ack!-----------deliveryTag=" + deliveryTag + "  multiple=" + multiple);
            }

            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                System.err.println("-------ack!-----------deliveryTag=" + deliveryTag + "  multiple=" + multiple);
            }
        });
    }
}
